package handlers

import (
    "context"
    "errors"
    "fmt"
    "log"
    "time"

    "github.com/dgrijalva/jwt-go"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    pb "your_project/proto"
    "your_project/data"
    "your_project/player"
)

// LoginHandler 处理登录相关请求
type LoginHandler struct {
    pb.UnimplementedLoginServiceServer
}

// NewLoginHandler 创建登录处理器实例
func NewLoginHandler() *LoginHandler {
    return &LoginHandler{}
}

// Login 处理玩家登录请求
func (h *LoginHandler) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
    log.Printf("Login request received for user: %s", req.Username)
    
    accountID, err := player.AuthenticatePlayer(req.Username, req.Password)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "Invalid credentials")
    }
    
    // 验证用户名和密码
    accountID, err := verifyCredentials(req.Username, req.Password)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "Invalid credentials")
    }
    
    // 获取玩家角色列表
    characters, err := getCharacters(accountID)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to get characters: %v", err)
    }
    
    if len(characters) == 0 {
        return nil, status.Errorf(codes.NotFound, "No characters found for account")
    }
    
    // 默认选择第一个角色
    selectedCharacter := characters[0]
    
    // 生成JWT令牌
    token, err := generateToken(accountID, selectedCharacter.CharacterID)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to generate token: %v", err)
    }
    
    // 构建响应
    resp := &pb.LoginResponse{
        Success:       true,
        Token:         token,
        PlayerId:      selectedCharacter.CharacterID,
        CharacterName: selectedCharacter.Name,
        Level:         selectedCharacter.Level,
        CharacterClass: selectedCharacter.Class,
        SceneId:       selectedCharacter.SceneID,
        Position:      &pb.Position{
            X: selectedCharacter.Position.X,
            Y: selectedCharacter.Position.Y,
            Z: selectedCharacter.Position.Z,
        },
    }
    
    return resp, nil
}

// verifyCredentials 验证用户凭证
func verifyCredentials(username, password string) (int64, error) {
    // 这里应该查询数据库验证用户名和密码
    // 简化示例,假设验证成功
    if username == "test" && password == "test" {
        return 12345, nil
    }
    
    return 0, errors.New("invalid credentials")
}

// getCharacters 获取用户角色列表
func getCharacters(accountID int64) ([]*player.Player, error) {
    // 从数据库加载角色列表
    // 简化示例,返回一个模拟角色
    players := []*player.Player{
        {
            ID:          67890,
            AccountID:   accountID,
            CharacterID: 67890,
            Name:        "TestPlayer",
            Level:       10,
            Class:       "Warrior",
            Health:      100,
            MaxHealth:   100,
            Position:    &pb.Position{X: 0, Y: 0, Z: 0},
            SceneID:     1,
            IsOnline:    false,
        },
    }
    
    return players, nil
}

// generateToken 生成JWT令牌
func generateToken(accountID, characterID int64) (string, error) {
    // 创建一个新的令牌对象,指定签名方法为HS256
    token := jwt.New(jwt.SigningMethodHS256)
    
    // 设置令牌声明
    claims := token.Claims.(jwt.MapClaims)
    claims["account_id"] = accountID
    claims["character_id"] = characterID
    claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
    
    // 生成签名的令牌
    tokenString, err := token.SignedString([]byte("your-secret-key"))
    if err != nil {
        return "", fmt.Errorf("failed to sign token: %v", err)
    }
    
    return tokenString, nil
}

// CreateCharacter 创建新角色
func (h *LoginHandler) CreateCharacter(ctx context.Context, req *pb.CreateCharacterRequest) (*pb.CreateCharacterResponse, error) {
    log.Printf("Create character request received for user: %s, name: %s", req.Username, req.CharacterName)
    
    // 验证用户名
    accountID, err := verifyUsername(req.Username)
    if err != nil {
        return nil, status.Errorf(codes.Unauthenticated, "Invalid username")
    }
    
    // 检查角色名是否已存在
    exists, err := checkCharacterNameExists(req.CharacterName)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to check character name: %v", err)
    }
    
    if exists {
        return nil, status.Errorf(codes.AlreadyExists, "Character name already exists")
    }
    
    // 创建新角色
    characterID, err := createNewCharacter(accountID, req.CharacterName, req.CharacterClass)
    if err != nil {
        return nil, status.Errorf(codes.Internal, "Failed to create character: %v", err)
    }
    
    return &pb.CreateCharacterResponse{
        Success:     true,
        Message:     "Character created successfully",
        CharacterId: characterID,
    }, nil
}

// verifyUsername 验证用户名
func verifyUsername(username string) (int64, error) {
    // 这里应该查询数据库验证用户名
    // 简化示例,假设验证成功
    if username == "test" {
        return 12345, nil
    }
    
    return 0, errors.New("invalid username")
}

// checkCharacterNameExists 检查角色名是否已存在
func checkCharacterNameExists(name string) (bool, error) {
    // 这里应该查询数据库检查角色名
    // 简化示例,假设角色名不存在
    return false, nil
}

// createNewCharacter 创建新角色
func createNewCharacter(accountID int64, name, class string) (int64, error) {
    // 这里应该将角色信息存入数据库
    // 简化示例,返回一个模拟角色ID
    return 67890, nil
}    